package io.itit.ecp.admin.provide.action.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.itit.ecp.admin.provide.action.resp.CommonLoginTokenResp;
import io.itit.ecp.admin.provide.action.resp.CommonLoginUserInfoResp;
import io.itit.ecp.admin.provide.action.resp.CommonLoginUserRoleResp;
import io.itit.ecp.admin.provide.utils.HttpClientUtil;
import io.itit.grass.common.exception.GrassException;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.server.entity.BaseEntity;
import io.itit.grass.common.server.helper.DictHelper;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.common.utils.CommonUtils;
import io.itit.grass.core.common.enums.IUserEnums;
import io.itit.grass.core.provide.action.req.UserReq;
import io.itit.grass.core.server.entity.RoleEntity;
import io.itit.grass.core.server.entity.UserEntity;
import io.itit.grass.core.server.entity.UserPostEntity;
import io.itit.grass.core.server.entity.UserRoleEntity;
import io.itit.grass.core.server.service.IRoleService;
import io.itit.grass.core.server.service.IUserPostService;
import io.itit.grass.core.server.service.IUserRoleService;
import io.itit.grass.core.server.service.IUserService;
import io.itit.grass.web.wall.action.controller.GrassWebController;
import io.itit.grass.web.wall.action.req.LoginReq;
import io.itit.grass.web.wall.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统一登录
 *
 * @Author：Roy
 * @Description：用户扩展控制类
 * @Date：Create by 2024-01-18 11:37:16
 */
@Slf4j
@Api(tags = "统一登录")
@RestController
@RequestMapping("/common/ecp-admin/unifiedLogin")
public class CommonLoginController {

    @Value("${cimLogin.grantType}")
    private String grantType;

    @Value("${cimLogin.redirectUrl}")
    private String redirectUri;

    @Value("${cimLogin.base64Incode}")
    private String base64Incode;

    @Value("${cimLogin.getTokenUrl}")
    private String getTokenUrl;

    @Value("${cimLogin.getUserInfoUrl}")
    private String getUserInfoUrl;

    @Value("${cimLogin.getUserRolesUrl}")
    private String getUserRolesUrl;

    @Value("${cimLogin.getUserFuncsUrl}")
    private String getUserFuncsUrl;

    @Resource
    private IUserService userService;

    @Resource
    private IUserPostService userPostService;

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private IRoleService roleService;

    @Resource
    private GrassWebController grassWebController;

    @ApiOperation("回调")
    @PostMapping("callback")
    public ResultResp queryPage(String code) {
        Map<String, String> haeders = new HashMap<>();
        haeders.put(HttpHeaders.AUTHORIZATION,"Basic "+base64Incode);
        haeders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
        // 通过code获取token
        String tokenRes = HttpClientUtil.sendPost(getTokenUrl, HttpClientUtil.buildAuthTokenBody(grantType, code, redirectUri), haeders);
        CommonLoginTokenResp tokenResp = JSON.parseObject(tokenRes, CommonLoginTokenResp.class);
        log.info("CommonLoginTokenResp:"+tokenResp.toString());
        // 通过token获取用户信息
        haeders.clear();
        haeders.put(HttpHeaders.AUTHORIZATION,"Bearer  "+tokenResp.getAccess_token());
        String userInfoRes = HttpClientUtil.sendPost(getUserInfoUrl, null, haeders);
        CommonLoginUserInfoResp userInfoResp = JSON.parseObject(userInfoRes, CommonLoginUserInfoResp.class);
        log.info("CommonLoginUserInfoResp:"+userInfoResp.toString());
        CommonLoginUserInfoResp.Content content = userInfoResp.getContent();
        CommonLoginUserInfoResp.User user = content.getUser();
        // 走原先登录逻辑
        UserEntity userEntity = userService.getOne(Wrappers.lambdaQuery(UserEntity.class)
                .eq(UserEntity::getDelFlag, IUserEnums.DelFlag.delFlag1.delFlag)
                .eq(UserEntity::getUserName, user.getLoginName()), false
        );
        LoginReq loginReq = new LoginReq();
        if(userEntity == null){
            // 如果不存在走新增账号
            String roleRes = HttpClientUtil.sendGet(getUserRolesUrl, haeders);
            CommonLoginUserRoleResp roleResp = JSON.parseObject(roleRes, CommonLoginUserRoleResp.class);
            UserReq req = buildUserReq("000", user.getUserName(), user.getLoginName(),roleResp);
            DictHelper.i().checkV("grass-core.user.status", req.getStatus());
            userEntity = (UserEntity)ConvertUtils.convertIgnoreId(req, UserEntity.class);
            if (StringUtils.isBlank(userEntity.getSaltCode())) {
                userEntity.setSaltCode(CommonUtils.getSaltNumberStr());
            }
            userEntity.setPassword(ShiroUtils.md5(req.getPassword(), userEntity.getSaltCode()));
            loginReq.setPassword(req.getPassword());

            if (saveUser(userEntity, req.getRoleIds(), req.getPostIds())) {
                loginReq.setUserName(userEntity.getUserName());
                loginReq.setPassword(req.getPassword());
            }else{
                loginReq.setUserName("admin");
                loginReq.setPassword("28a6e24cd6ffe1b36e8eb424b4605ddc");
            }
        }else{
            System.out.println(userEntity);
            // 是否被禁用
            if (Objects.equals(userEntity.getStatus(), IUserEnums.Status.status2.status)) {
                throw new GrassException("用户已禁用!");
            }
            loginReq.setUserName("admin");
            loginReq.setPassword("28a6e24cd6ffe1b36e8eb424b4605ddc");
        }
        return grassWebController.login(loginReq);
    }

    public boolean saveUser(UserEntity userEntity,Set<String> roleIds,Set<String> postIds){
        this.userService.save(userEntity);
        if (!CollectionUtils.isEmpty(postIds)) {
            List<UserPostEntity> postDtoList = new ArrayList();
            Iterator var4 = postIds.iterator();

            while(var4.hasNext()) {
                String postId = (String)var4.next();
                UserPostEntity userPostEntity = new UserPostEntity();
                userPostEntity.setUserId(userEntity.getId());
                userPostEntity.setPostId(postId);
                postDtoList.add(userPostEntity);
            }
            this.userPostService.saveBatch(postDtoList);
        }
        if (CollectionUtils.isEmpty(roleIds)) {
            return Boolean.TRUE;
        } else {
            roleIds = this.checkRole(roleIds);
            if (CollectionUtils.isEmpty(roleIds)) {
                return Boolean.TRUE;
            }
            List<UserRoleEntity> roleDtoList = new ArrayList();
            try {
                Iterator var5 = roleIds.iterator();
                while(var5.hasNext()) {
                    String roleId = (String)var5.next();
                    UserRoleEntity userRoleEntity = new UserRoleEntity();
                    userRoleEntity.setUserId(userEntity.getId());
                    userRoleEntity.setRoleId(roleId);
                    roleDtoList.add(userRoleEntity);
                }
                return this.userRoleService.saveBatch(roleDtoList);
            }catch (Exception e){
                e.printStackTrace();
                log.error("保存用户角色报错：" + e.toString());
            }
        }
        return Boolean.TRUE;
    }

    private Set<String> checkRole(Set<String> roleIds) {
        Set<String> allRoleIds = this.roleService.list(Wrappers.lambdaQuery(RoleEntity.class).select(BaseEntity::getId)).stream().map(BaseEntity::getId).collect(Collectors.toSet());
        Set<String> haveRoleIds = new HashSet<>();
        roleIds.stream().forEach(roleId -> {
            if(allRoleIds.contains(roleId)){
                haveRoleIds.add(roleId);
            }
        });
        return haveRoleIds;
//        if (!roleIds.stream().allMatch((t) -> {
//            return allRoleIds.contains(t);
//        })) {
//            GrassCoreException.throwEx("疑似越权操作，请刷新页面后重试！");
//        }
    }

    public UserReq buildUserReq(String deptId,String fullName,String userName,CommonLoginUserRoleResp roleResp){
        UserReq userReq = new UserReq();
        userReq.setStatus(IUserEnums.Status.status1.status);
        userReq.setDeptId(deptId);
        userReq.setFullName(fullName);
        userReq.setUserName(userName);
        HashSet<String> roleIds = new HashSet<>();
        List<CommonLoginUserRoleResp.Role> roleList = roleResp.getContent();
        roleList.stream().forEach(role -> {
            String[] split = role.getRoleCode().split("-");
            roleIds.add(split[split.length - 1]);
        });
        userReq.setRoleIds(roleIds);
        // 初始密码 a88888888 md5加密后的结果
        userReq.setPassword("e561b513e138eaf2e9cfde2784ef14ca");
        return userReq;
    }

}
